<template>
  <div>
    <wxc-overlay
          :show="this.attributesVisiabled"
          opacity="0.6"
          @wxcOverlayBodyClicking="wxcOverlayBodyClicking"
          ></wxc-overlay>
    <div class="attributes-wrapper" :class="[this.attributesVisiabled ? 'show' : 'hide']">
      <div class="header">
        <text class="title">{{this.food.title}}</text>
        <button class="btn-close iconfont icon-close" @click="handleClose"></button>
      </div>
      <scroller class="lists">
        <div v-for="(v,index) in this.food.attributes"
            :key="index"
            :data-id="index"
            class="list-items">
          <text class="item-title">{{v.title}}:</text>
          <div class="item">
            <wxc-grid-select
              :single="!Boolean(v.isSingle)"
              :customStyles="customStyles"
              :list="v.models"
              :limit="v.onOverLimit"
              @select="params => onSelect(params, index, !Boolean(v.isSingle))">
            </wxc-grid-select>
          </div>
        </div>
      </scroller>
      <div class="footer">
        <text class="price" v-if="this.food.price" :class="food.price.symbol">{{this.defaultPrice}}</text>
        <div class="count-stepper" v-if="this.inShoppingCart">
          <wxc-stepper
            max="99"
            min="0"
            :read-only="true"
            :default-value="this.num"
            @wxcStepperValueIsMinOver="editShoppingCart(0)"
            @wxcStepperValueChanged="event => wxcStepperValueChanged(event)"
            ></wxc-stepper>
        </div>
        <div class="add-shopping-cart" v-else @click="editShoppingCart(1)">
          <text>{{language.add}}</text>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
  .item {
    .grid-select {
      .grid-option {
        border-radius: 30px;
        min-width:130px !important;
        width: auto !important;
        margin-top: 15px !important;
        .text-title {
          font-size: 24px;
        }
      }
    }
  }

  .count-stepper {
    .wxc-stepper {
      .stepper-plus {
        background-color: #f45551;
        border-radius: 0 20px 20px 0;

        .stepper-icon {
          color: #FFFFFF !important;
          margin-top: 0;
        }
      }

      .stepper-minus {
        background-color: #f45551;
        border-radius: 20px 0 0 20px;

        .stepper-icon {
          color: #FFFFFF !important;
          margin-top: 0;
        }
      }

      .stepper-input {
        background-color: #f45551;
        color: #FFFFFF;
        border: 0.5px dotted #ffffff;
        border-top: none;
        border-bottom: none;
        outline: none;
        border-radius: 0;

        &:disabled {
          color: #ffffff;
          -webkit-text-fill-color:#ffffff;
          -webkit-opacity:1;
          opacity: 1;
        }
      }
    }
  }
</style>

<style lang="scss" scoped>
  .attributes-wrapper {
    position: fixed;
    top: 10%;
    left: 40px;
    right: 40px;
    background-color: #FFFFFF;
    border-radius: 20px;
    overflow: hidden;

    &.hide {
      display: none;
    }

    &.show {
      animation: topIn .6s ease;
      display: block;
    }

    .header {
      position: relative;
      padding: 30px;

      .title {
        text-align: center;
      }

      .btn-close {
        background-color: unset;
        width: fit-content;
        color: #000000;
        font-size: 32px;
        outline: none;
        position: absolute;
        right: 10px;
      }
    }

    .lists {
      padding: 30px;
      height:900px;
      .list-items {
        padding-bottom: 40px;

        .item-title {
          font-size: 20px;
          color: #757575;
          padding-bottom: 20px;
        }
      }
    }

    .footer {
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      background-color: #f2f2f2;
      padding: 30px;
      border-bottom-left-radius: 20px;
      border-bottom-right-radius: 20px;

      .price {
        font-size: 46px;
        color: #f45551;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: baseline;

        &.yen {
          &:before {
            content: "¥";
            font-size: 30px;
            padding-right: 10px;
          }
        }

        &.mop {
          &:before {
            content: "mop";
            font-size: 30px;
            padding-right: 5px;
          }
        }
      }

      .add-shopping-cart {
        border: 1px solid #f45551;
        border-radius: 40px;
        background-color: #f45551;
        padding: 10px 30px;

        > p {
          font-size: 20px;
          color: #ffffff;
        }
      }
    }
  }

  @keyframes topIn {
    from {
      transform: translate(0, -50%);
      opacity: 0;
    }

    to {
      transform: translate(0, 0);
      opacity: 1;
      display: block;
    }
  }
</style>

<script>
import { WxcOverlay, WxcGridSelect, WxcStepper } from 'weex-ui'
import { i18n } from '@/renderer/modules/lang'
export default {
  components: { WxcOverlay, WxcGridSelect, WxcStepper },
  props: {
    food: {
      type: Object,
      default: () => ({
        attributes: [],
        avatar: '',
        price: {
          amount: '0',
          symbol: 'mop'
        },
        sales: '0',
        title: ''
      })
    },
    attributesVisiabled: {
      type: Boolean,
      default: false
    },
    categoryIndex: {
      type: Number
    },
    foodIndex: {
      type: Number
    },
    itemIndex: {
      type: Number
    }
  },
  data: () => ({
    customStyles: {
      lineSpacing: '24px',
      width: '130px',
      height: '50px',
      icon: '',
      color: '#333333',
      checkedColor: 'rgba(244,85,81,1)',
      disabledColor: '#eeeeee',
      borderColor: '#dfdfdf',
      backgroundColor: '#ffffff',
      checkedBorderColor: 'rgba(244,85,81,1)',
      checkedBackgroundColor: 'rgba(244,85,81,0.1)',
      checkedOpacity:0.5
    },
    language: {
      add: i18n.t('arrtibutes.add')
    },
    defaultPrice: 0,
    defaultAttributesVisiabled: false,
    inShoppingCart: false,
    attributesPrice: [],
    num: 1,
    shoppingCartData: localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}
  }),
  watch: {
    food (newFood, oldFood) {
      let price = 0
      let shoppingCart = localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}
      let attributeKey = []
      this.food = newFood
      this.defaultPrice = newFood.price.amount
      newFood.attributes.forEach(attribute => {
        attribute.models.forEach((model, index) => {
          if (index === 0) {
            model.checked = true
            price = (parseFloat(price) + parseFloat(model.price)).toFixed(2)
            attributeKey.push(model.model_id)
          } else {
            model.checked = false
          }

          this.attributesPrice[attributeKey] = (parseFloat(model.price)).toFixed(2)
        })
      })

      this.inShoppingCart = false

      if (shoppingCart[newFood.food_id]) {
        attributeKey = attributeKey.join('-')
        if (shoppingCart[this.food.food_id].attributes[attributeKey]) {
          this.inShoppingCart = true
          this.num = shoppingCart[this.food.food_id].attributes[attributeKey].number
        }
      }

      this.defaultPrice = (parseFloat(this.defaultPrice) + parseFloat(price)).toFixed(2)
    }
  },
  methods: {
    handleClose (e) {
      this.$emit('changeAttributesVisiabled', this.defaultAttributesVisiabled)
    },
    handleFoodNumberInShoppingCart () {
      this.$emit('changeFoodNumberInShoppingCart', this.categoryIndex, this.foodIndex)
    },
    wxcOverlayBodyClicking (e) {
      this.$emit('changeAttributesVisiabled', this.defaultAttributesVisiabled)
    },
    onSelect ({selectIndex, checked, checkedList}, attributeIndex, isSingle) {
      let modelPrice = 0
      let key = []
      let shoppingCart = JSON.parse(localStorage.getItem('shoppingCart'))
      if (isSingle) {
        this.food.attributes[attributeIndex].models.forEach((model, modelIndex) => {
          this.food.attributes[attributeIndex].models[modelIndex].checked = false
        })
      }

      this.food.attributes[attributeIndex].models[selectIndex].checked = checked

      this.food.attributes.forEach((attribute, index) => {
        attribute.models.forEach(model => {
          if (model.checked) {
            key.push(model.model_id)
            modelPrice = (parseFloat(model.price) + parseFloat(modelPrice)).toFixed(2)
          }
        })
      })

      this.inShoppingCart = false

      if (shoppingCart && shoppingCart[this.food.food_id]) {
        key = key.join('-')
        if (shoppingCart[this.food.food_id].attributes[key]) {
          this.inShoppingCart = true
          this.num = shoppingCart[this.food.food_id].attributes[key].number
        }
      }

      this.defaultPrice = (parseFloat(this.food.price.amount) + parseFloat(modelPrice)).toFixed(2)
    },
    wxcStepperValueChanged (event, index, key) {
      this.editShoppingCart(event.value)
    },
    editShoppingCart (num) {
      let shoppingCartData = localStorage.getItem('shoppingCart') ? JSON.parse(localStorage.getItem('shoppingCart')) : {}
      let attributeKey = []
      let attributeTitle = []
      let attrs = []
      this.food.attributes.forEach((attribute, index) => {
        let models = []
        attribute.models.forEach(model => {
          if (model.checked) {
            models.push(model.model_id)
            attributeTitle.push(model.title)
            attributeKey.push(model.model_id)
          }
        })
        attrs.push({attr_id: attribute.attribute_id, models: models})
      })

      attributeKey = attributeKey.join('-')
      attributeTitle = attributeTitle.join('、')

      if (!shoppingCartData[this.food.food_id]) shoppingCartData[this.food.food_id] = {}
      shoppingCartData[this.food.food_id].title = this.food.title
      if (!shoppingCartData[this.food.food_id].attributes) shoppingCartData[this.food.food_id].attributes = {}

      if (num < 1) {
        this.inShoppingCart = false
        delete shoppingCartData[this.food.food_id]['attributes'][attributeKey]
      } else {
        shoppingCartData[this.food.food_id]['attributes'][attributeKey] = {
          title: attributeTitle,
          number: num,
          unitPrice: this.defaultPrice,
          attrs: attrs
        }
        this.inShoppingCart = true
      }

      let foodNum = 0
      for (let key in shoppingCartData[this.food.food_id]['attributes']) {
        foodNum = parseFloat(foodNum) + parseFloat(shoppingCartData[this.food.food_id]['attributes'][key].number)
      }
      shoppingCartData[this.food.food_id].number = foodNum
      shoppingCartData[this.food.food_id].avatar = this.food.avatar
      shoppingCartData[this.food.food_id].symbol = this.food.price.symbol
      this.num = num

      localStorage.setItem('shoppingCart', JSON.stringify(shoppingCartData))

      this.handleFoodNumberInShoppingCart()
    }
  }
}
</script>
